package cn.zhumingjin.powermeter.controller;

import cn.zhumingjin.powermeter.controller.vo.LoginVo;
import cn.zhumingjin.powermeter.controller.vo.LayUIVo;
import cn.zhumingjin.powermeter.controller.vo.UserVo;
import cn.zhumingjin.powermeter.entity.User;
import cn.zhumingjin.powermeter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
@RestController
public class UserController {
    @Autowired
    public UserService userService;

    @RequestMapping(path = "/getAllUsers", method = RequestMethod.POST)
    @ResponseBody
    public LayUIVo getUsers(){
        System.out.println("/getAllUsers");
        List<User> list = userService.getUsers();
        ArrayList<UserVo> result = new ArrayList<>();
        for (User user : list) {
            result.add(new UserVo(user.getId(), user.getName(),
                    user.getPassword(), user.getPrivilege()));

        }
        return new LayUIVo<>(0, "", result.size(), result);
    }



    @RequestMapping(path = "/login", method = RequestMethod.POST)  //方法映射路径
    @ResponseBody  //将返回信息输送到网页端
    public LoginVo login(@RequestParam(name = "id") Integer id,
                         @RequestParam(name="password") String password) {
        System.out.println("/login");
        User user = userService.login(id, password);
        LoginVo result;
        if (user != null)
            result = new LoginVo(0, user.getId(), user.getPrivilege(), user.getName());
        else result = new LoginVo(1, null, null, null);
        return result;
    }
}
